import AxiosMethods from "@/util/AxiosMethods";

const state = {
    Contributions: []
};

const getters = {};

const mutations = {
    // 获取用户捐款数据到当前 store
    SET_USER_CONTRIBUTIONS(state, contributions) {
        state.Contributions = contributions;
    }
};

const actions = {
    // 获取某个用户的捐款数据
    async getUserContributions({ commit }, uid) {
        try {
            const response = await AxiosMethods.post("/contribution/select", { uid: uid });
            if (response.data.code === 1) {
                // console.log("接收到的捐款数据：", response.data.data);
                commit('SET_USER_CONTRIBUTIONS', response.data.data); // 将数据提交到 mutations
            } else {
                console.log("获取捐款数据失败：", response.data.msg);
                commit('SET_USER_CONTRIBUTIONS', []); // 若获取失败则清空数据
            }
        } catch (error) {
            console.log(error);
            commit('SET_USER_CONTRIBUTIONS', []); // 异常处理，清空数据
        }
    },
    // 删除某个捐款数据
    async deleteContribution({ commit }, cid) {
        // console.log("删除的捐款数据 id：", cid);
        try{
            const response = await AxiosMethods.delete(`/contribution/${cid}`);
            if(response.data.code === 1){
                console.log("删除成功");
                location.reload(); // 刷新页面
            }
        }catch(error){
            console.log(error);
        }
    },
    // 增加某个项目的捐款数据
    async addContribution({ commit }, data) {
        console.log("增加的捐款数据：", data);
        try{
            const response = await AxiosMethods.post("/contribution/add", data);
            if(response.data.code === 1){
                console.log("捐款成功");
                return true;
            }
        }catch(error){
            console.log(error);
        }
    }
};

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}
